<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/15
 * Time: 10:29
 */

namespace app\common\model;
use think\exception\HttpException;

class Verify
{

    /**
     * @param $clientId
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getSecret($clientId){
        if(empty($clientId)){
            throw new HttpException(200,'clientId不能为空');
        }
        $redis=new Redis();
        $secret=$redis->hGet('secret',$clientId);
        if(empty($secret)){
            $secret=\think\Db::name('client_node')->where(['status'=>1,'client_id'=>$clientId])->find();
            if($secret){
                $redis->hSet('secret',$clientId,$secret['secret']);
                return $secret['secret'];
            }else{
                throw new HttpException(200,'签名秘钥未设置');
            }
        }else{
            return $secret;
        }
    }

    /**
     * 验证md5签名
     * 签名方法:将所有参数按升序排列,最后加上secret=签名秘钥,再计算md5.clientId为必传参数
     * @param array $data
     * @param string $type
     * @return bool
     */
    static public function verify(array $data,$type='md5'){
        //return true;
        if(empty($data)){
            throw new HttpException(200,'没有收到任何参数');
        }
        if(empty($data['sign'])){
            throw new HttpException(200,'sign不能为空');
        }
        if(empty($data['clientId'])){
            throw new HttpException(200,'clientId不能为空');
        }
        $secret=self::getSecret($data['clientId']);
        if(empty($secret)){
            throw new HttpException(200,'签名秘钥未设置');
        }
        $sign=trim($data['sign']);
        $params=$data;
        unset($params['sign']);
        unset($params['echo']);
        unset($params['XDEBUG_SESSION_START']);
        ksort($params);
        $str='';
        foreach($params as $k=>$v){
            $str.=$k.'='.$v.'&';
        }
        $str.='secret='.$secret;
        //throw new HttpException(200,$str);

        return strtolower($sign)==strtolower(md5($str));
    }
}